package logs

import (
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

//设置日志级别，输出格式和文件路径
func SetLogs(level zapcore.Level, logFormat, logUrl string, size, backups, age int, compress bool) {
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        TIME_KEY,
		LevelKey:       LEVLE_KEY,
		NameKey:        NAME_KEY,
		CallerKey:      CALLER_KEY,
		MessageKey:     MESSAGE_KEY,
		StacktraceKey:  STACKTRACE_KEY,
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalLevelEncoder,    // 大写编码器
		EncodeTime:     zapcore.ISO8601TimeEncoder,     // ISO8601 UTC 时间格式
		EncodeDuration: zapcore.SecondsDurationEncoder, //
		EncodeCaller:   zapcore.ShortCallerEncoder,     // 短路径编码器(相对路径+行号)
		EncodeName:     zapcore.FullNameEncoder,
	}

	//设置文件输出格式
	var encoder zapcore.Encoder
	switch logFormat {
	case LOGFORMAT_JSON:
		encoder = zapcore.NewJSONEncoder(encoderConfig)
	default:
		encoder = zapcore.NewConsoleEncoder(encoderConfig)
	}
	//添加日志切割归档功能
	hook := lumberjack.Logger{
		Filename:   logUrl,   // 日志文件路径
		MaxSize:    size,     // 每个日志文件保存的最大尺寸 单位：M
		MaxBackups: backups,  // 日志文件最多保存多少个备份
		MaxAge:     age,      // 文件最多保存多少天
		Compress:   compress, // 是否压缩
	}
	core := zapcore.NewCore(
		encoder, //编码器配置
		zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stderr), zapcore.AddSync(&hook)), //打印到控制台和文件
		zap.NewAtomicLevelAt(level), //日志级别
	)
	//开启文件及行号
	caller := zap.AddCaller()
	//开启开发模式，堆栈跟踪
	development := zap.Development()
	//构造日志
	logger := zap.New(core, caller, development)
	//将自定义的logger替换成全局的Logger
	zap.ReplaceGlobals(logger)
}
